#include "WordLib.h"
#include "_Global/GlobalClass.h"

#include <QSqlQuery>

WordLib::WordLib(QObject *parent) : QObject(parent)
{
    m_nType = -1;
    m_nClassID = -1;
    m_nLevelID = -1;
    m_pnComputerWords = nullptr;

    init();
}

WordLib::~WordLib()
{
    deleteAll();

    if(m_pnComputerWords != nullptr)
        delete m_pnComputerWords;
}

void WordLib::init()
{
    m_nWordCount = 0;
    m_nMistakeCount = 0;
    m_nCorrectCount = 0;

    m_nFastChoice = 0;
    m_nContinualChoice = 0;
    m_nContinualStatistics = 0;

    m_nStudyType = 0;
    m_strResult.clear();
}

void WordLib::Debug(QString msg)
{
    qDebug() << msg;
}


void WordLib::deleteAll()
{
    qDeleteAll(m_listWord);
    m_listWord.clear();
}
/*
bool WordLib::getAnswersCount(int &correct, int &mistake)
{
    QList<_EnglishWord*>::const_iterator ii;
    correct = 0;
    mistake = 0;
    for (ii = m_listWord.constBegin(); ii != m_listWord.constEnd(); ++ii)
    {
        if((*ii)->myAnswer != -2)
        {
           if((*ii)->answer != (*ii)->myAnswer)
               mistake++;
           else
               correct++;
        }
    }
    return true;
}*/
/*
_EnglishWord *WordLib::createNewWord()
{
    if(isValid())
    {
        QSqlQuery query(*m_pDB);  //查询
        int nCount;

        / *
        if (!query.exec("CREATE TABLE student ("
            "id INTEGER PRIMARY KEY AUTOINCREMENT,"
            "name VARCHAR,"
            "age INT)"))
        {
            QMessageBox::critical(0, QObject::tr("Database Error"),
                         query.lastError().text());
            return 1;
        }
        * /


//得到个数
        if(!query.exec("SELECT count(*) As TotalCount FROM English"))
        {
            showError("Query1 Error");
            return nullptr;
        }

        query.seek(0);
        nCount = query.value("TotalCount").toInt();
        query.finish();


//选词
        if(!query.exec("SELECT * FROM English"))
        {
            showError("Query2 Error");
            return nullptr;
        }


        _EnglishWord *pWord = new _EnglishWord;

        long nValues[4];
        GetDifferentNumber(0,nCount,nValues,4);   //得到4个不相同随机数
//QString::compare("df","ab",Qt::CaseInsensitive);

        int answer = Random(0,4);       //答案
        for(int i = 0; i < 4; i++)
        {
            query.seek(nValues[i]);  //query默认从-1开始,0是第一条
            if(i == answer)
            {
                pWord->word = query.value("Word").toString();
                pWord->m_strPhonetic = query.value("Phonetic").toString();
                pWord->m_strExplain.append(query.value("Explain").toString());
                pWord->answer = answer;
            }
            else    //设置错误答案
            {
                pWord->m_strExplain.append(query.value("Explain").toString());
            }
        }
        pWord->answerChoice = -1;

        query.finish();
        //m_pDB->close();
        return pWord;
    }
    else
    {
        return nullptr;
    }
    return nullptr;
}*/

bool WordLib::createWords(int classID, int levelID)
{
    /*
    if(classID == m_nClassID || levelID == m_nLevelID)
    {
        QList<_EnglishWord*>::Iterator ii;
        for(ii = m_listWord.begin(); ii != m_listWord.end(); ii++)
        {
            //(*ii)->myAnswer = -1;
        }
    }*/

    if(isValid())
    {
        deleteAll();

        m_nClassID = classID;
        m_nLevelID = levelID;

        if(classID > 8 && classID < 17)
        {
            classID -= 8;
        }

        QSqlQuery query(*m_pDB);  //查询

        QString sql = QString("SELECT * FROM WordInfo_English WHERE ClassID=%1 AND LevelID=%2").arg(classID).arg(levelID);
        if(!query.exec(sql))
        {
            showError("Query1 Error");
            return false;
        }

        while(query.next())
        {
            _EnglishWord *pWord = new _EnglishWord;
            pWord->m_nID = query.value("id").toInt();

            if(m_nType == 1)
            {
                pWord->m_strWord = query.value("Word").toString();
                pWord->m_strExplain = query.value("Explain").toString();
            }

            else if(m_nType == 2)
            {
                pWord->m_strWord = query.value("Explain").toString();
                pWord->m_strExplain = query.value("Word").toString();
            }

            //pWord->myAnswer = -1;
            m_listWord.append(pWord);
        }
        query.finish();
        m_nWordPointer = -1;

        if(m_pnComputerWords != nullptr)
            delete m_pnComputerWords;

        m_pnComputerWords = new int[m_listWord.length()];
        GetDifferentNumber(0, m_listWord.length(), m_pnComputerWords, m_listWord.length(), sizeof(int));
        m_nComputerWordPointer = 0;

        return true;
    }
    else
    {
        showError("Database Error");
        return false;
    }

    return true;
}

int WordLib::getWordCount(int classID, int levelID)
{
    if(classID > 8 && classID < 17)
    {
        classID -= 8;
    }

    if(classID == m_nClassID || levelID == m_nLevelID)
    {
        return m_listWord.length();
    }

    int count = 0;
    if(isValid())
    {
        QSqlQuery query(*m_pDB);  //查询
        QString sql = QString("SELECT COUNT(*) AS WordCount FROM WordInfo_English WHERE ClassID=%1 AND LevelID=%2").arg(classID).arg(levelID);
        if(!query.exec(sql))
        {
            showError("Query1 Error");
            return -1;
        }

        if(query.next())
        {
            count = query.value("WordCount").toInt();
        }
        query.finish();

        return count;

    }
    else
    {
        showError("Database Error");
        return -1;
    }
}

bool WordLib::getWord(_WordObject* pWordObj, bool userWord)
{
    if(pWordObj == nullptr)
    {
        return false;
    }

    //单词指针
    if(userWord == true)
    {
        if(m_nWordPointer >= m_listWord.length())
            return false;
        pWordObj->m_pWord = m_listWord[m_nWordPointer];
    }
    else
    {
        //pWordObj->m_pWord = m_listWord[Random(0,m_listWord.length())];
        pWordObj->m_pWord = m_listWord[m_pnComputerWords[m_nComputerWordPointer]];
        m_nComputerWordPointer = (m_nComputerWordPointer + 1) % m_listWord.length();
    }

    pWordObj->m_listExplain.clear();
    //pWordObj->m_ExplainIdList.clear();



    //提取4个随机数,并且保证3个id和单词id不同
    qint32 nValues[4];
    if(!GetDifferentNumber(0,m_listWord.length(),nValues,4,sizeof(qint32)))   //得到4个不相同随机数
    {
        Debug("随机范围出错");
        return false;
    }

    //保证nValues前3个是错误id
    int i;
    for(i = 0; i < 3; i++)  //将前3个设置为错误答案id
    {
        if(pWordObj->m_pWord->m_nID == m_listWord.at(nValues[i])->m_nID)  //如果第i个单词id和错误id相同,则设置第3个错误单词id到i
        {
            nValues[i] = nValues[3];
            break;
        }
    }
    //QString::compare("df","ab",Qt::CaseInsensitive);


    pWordObj->m_nAnswer = (qint16)Random(0,4);       //随机选出答案下标
    int j = 0;
    for(i = 0; i < 4; i++)
    {
        if(i == pWordObj->m_nAnswer)
        {
            pWordObj->m_listExplain.append(pWordObj->m_pWord->m_strExplain);

            //pWordObj->m_ExplainIdList.append(pWordObj->m_pWord->id);
            pWordObj->m_nAnswerChoice = -1;
        }
        else    //设置错误答案
        {
            pWordObj->m_listExplain.append(m_listWord.at(nValues[j])->m_strExplain);

            //pWordObj->m_ExplainIdList.append(m_listWord.at(nValues[j])->id);
            j++;
        }
    }

    //m_pDB->close();
    return true;
}

bool WordLib::moveToNextWord()
{
    if(m_nStudyType == 1)
    {
        for(m_nWordPointer++; m_nWordPointer < m_listWord.length(); m_nWordPointer++)
            if(m_strResult.at(m_nWordPointer) == 'u')
                break;
        if(m_nWordPointer == m_listWord.length())
            return false;
        else
            return true;
    }

    else if(m_nStudyType == 2)
    {
        for(m_nWordPointer++; m_nWordPointer < m_listWord.length(); m_nWordPointer++)
            if(m_strResult.at(m_nWordPointer) == 'n')
                break;
        if(m_nWordPointer == m_listWord.length())
            return false;
        else
            return true;
    }
    else
    {
        qDebug()<<"moveToNextWord Error!!!"<<m_nStudyType;
        return false;
    }
}


bool WordLib::createWord(_WordObject* pWordObj, int correctID, int wordsID[])
{
    if(pWordObj == nullptr)
    {
        return false;
    }

    if(isValid())
    {
        QString ids = QString::number(wordsID[0]);
        for(int i = 1; i < 4; i++)
            ids.append("," + QString::number(wordsID[i]));

        QSqlQuery query(*m_pDB);  //查询

        QString sql = QString("SELECT * FROM WordInfo_English WHERE id IN (%1)").arg(ids);
        if(!query.exec(sql))
        {
            showError("createWord Query Error");
            return false;
        }


        pWordObj->m_listExplain.clear();

        int i = 0;
        while(query.next())
        {
            if( correctID == i )    //正确答案
            {
                pWordObj->m_pWord->m_nID = query.value("id").toInt();
                if(m_nType == 1)
                {
                    pWordObj->m_pWord->m_strWord = query.value("Word").toString();
                    pWordObj->m_pWord->m_strExplain = query.value("Explain").toString();
                }
                else if(m_nType == 2)
                {
                    pWordObj->m_pWord->m_strWord = query.value("Explain").toString();
                    pWordObj->m_pWord->m_strExplain = query.value("Word").toString();
                }
                //pWord->myAnswer = -1;
                pWordObj->m_nAnswer = correctID;
                pWordObj->m_nAnswerChoice = -1;
            }
            if(m_nType == 1)
            {
                pWordObj->m_listExplain.append(query.value("Explain").toString());
            }
            else if(m_nType == 2)
            {
                pWordObj->m_listExplain.append(query.value("Word").toString());
            }
            i++;
        }
        query.finish();

        return true;

    }
    else
    {
        showError("createWord Database Error");
        return false;
    }

    return true;
}

bool WordLib::setResult(QString r)
{
    /*
    m_CorrectCount = 0;
    QString::const_iterator ii;
    for(ii = r.constBegin(); ii != r.constEnd(); ii++)
        if(*ii == 'y')m_CorrectCount++;
    return true;*/

    if(r == "")    //没学过
    {
        m_strResult.fill('u',m_listWord.length());
    }
    else
        m_strResult = r;


    /*
    else
    {
        if(m_nStudyType == 2)    //复习
        {
            //if(m_strResult.contains('u'))    //如果有没学完的
            //    m_strResult.replace(QString("n"),QString("u"));
        }
    }*/
    return true;
}
/*
QString WordLib::createResult()
{
    if(m_listWord.isEmpty())return "";
    int i = 0;
    m_strResult.clear();
    for(; i < m_listWord.length(); i++)
    {
        if(m_listWord.at(i)->myAnswer == 1)
            m_strResult.append('y');
        else if(m_listWord.at(i)->myAnswer == 0)
            m_strResult.append('n');
        else
            m_strResult.append('u');
    }
    return m_strResult;
}*/
